import json
import random
import time

from paho.mqtt import client as mqtt_client


# def on_connect(client, userdata, flags, rc):
#     global FLAG_CONNECTED
#     if rc == 0:
#         FLAG_CONNECTED = 1
#         print("Connected to MQTT Broker!")
#     else:
#         print("Failed to connect, return code {rc}".format(rc=rc), )

class MQTTSend:
    """ 创建一个专门用来发送消息到 MQTT 服务器的模块"""
    BROKER = 'b69e40c8.cn.emqx.cloud'
    PORT = 11876
    # generate client ID with pub prefix randomly
    CLIENT_ID = "python-mqtt-tcp-pub-{id}".format(id=random.randint(0, 1000))
    USERNAME = 'test'
    PASSWORD = 'test'
    FLAG_CONNECTED = 0

    def __init__(self):
        self.client = self.connect_mqtt()

    def connect_mqtt(self):
        client = mqtt_client.Client(MQTTSend.CLIENT_ID)
        client.username_pw_set(MQTTSend.USERNAME, MQTTSend.PASSWORD)
        # client.on_connect = on_connect
        client.connect(MQTTSend.BROKER, MQTTSend.PORT)
        return client

    def Heartbeat(self):
        # 心跳包
        self.client.publish("Heartbeat", json.dumps({"Heartbeat": "1"}))

    def sendData(self, topic: str, data: dict):
        result = self.client.publish(topic, json.dumps(data))
        # result: [0, 1]
        status = result[0]
        if status == 0:
            return True  # 发送成功
        else:
            return False  # 发送失败


if __name__ == '__main__':
    mqtt = MQTTSend()
    while True:
        mqtt.Heartbeat()
        data = [
            {
                "nodenum": "DHT11-2",
                "hum": random.randint(75, 100),
                "tem": random.randint(0, 25),
                "nodestate": "正常"
            },
            {
                "nodenum": "18B20",
                # "hum": random.randint(75, 100),
                "tem": random.randint(0, 25),
                "nodestate": "正常"
            },

        ]
        mqtt.sendData("CGQ-data", data)
        time.sleep(5)
